#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 200 };

Server server(6301);

uint8_t cmd[100];
uint8_t iCmd=0;

//Arduino ports configurazion
const uint8_t      PORT_SHIFTOUT_LATCH = 7;
const uint8_t      PORT_SHIFTOUT_CLOCK = 8;
const uint8_t      PORT_SHIFTOUT_DATA  = 9;

int output;

void setup() {
  pinMode(PORT_SHIFTOUT_LATCH, OUTPUT);
  pinMode(PORT_SHIFTOUT_CLOCK, OUTPUT);
  pinMode(PORT_SHIFTOUT_DATA, OUTPUT);
  
  output=0;
  sendData(output);
  
  Serial.begin(9600);
  
  Ethernet.begin(mac, ip);
  server.begin();
}

void loop() {
  Client client = server.available();
  if (client) {
    char c;
    do {
      c = client.read();
      Serial.print(millis());
      Serial.print(" ricevuto: ");
      Serial.println((int)c);
      if (c==0) {
        //client.stop();
        executeCmd();
        iCmd=0;
      }
      else if (c != -1) {
        cmd[iCmd++]=c;
      }
    } while (c != -1);
    Serial.print("Fine : ");
    Serial.println(millis());
  }
}

void executeCmd() {
  if (cmd[0] == 1) {
    Serial.println((int)cmd[1]);
    if (bitRead(output, cmd[1]) == 0)
      bitWrite(output, cmd[1], 1);
    else
      bitWrite(output, cmd[1], 0);
    sendData(output);
  }
  else if (bitRead(cmd[0], 7)==1) {
    uint8_t newStatus = bitRead(cmd[0], 0);
    uint8_t address = (cmd[0]>>1) & B00111111;
    //Serial.println(int(address));
    //Serial.println(int(newStatus));
    bitWrite(output, address, newStatus);
    sendData(output);
  } 
}

void sendData(int data) {
  digitalWrite(PORT_SHIFTOUT_LATCH, LOW);
  shiftOut(PORT_SHIFTOUT_DATA, PORT_SHIFTOUT_CLOCK, LSBFIRST, data&255);   
  shiftOut(PORT_SHIFTOUT_DATA, PORT_SHIFTOUT_CLOCK, LSBFIRST, data>>8);   
  digitalWrite(PORT_SHIFTOUT_LATCH, HIGH); 
}
